package p3.code;

public class SingletonExa {


    // 引用类型
    private final String[] states = {"c","a","r"};

    /**
     * 安全的对象发布
     */
    public String[] getStates() {
        String[] res = new String[states.length];
        System.arraycopy(states,0,res,0,states.length);
        return res;
    }

    public void set(int index,String element){
        states[index] = element;
    }

    //构造函数私有保证实例只能由此类的方法产生
    private SingletonExa(){}

    //单例对象
    private static SingletonExa instance = null;

    //静态工厂方法
    public static SingletonExa getInstance1() {
        // 这里存在问题，如果两个线程同时第一次进入，
        // 那么instance就会被实例化两次！！
        if(instance == null) {
            instance = new SingletonExa();
        }
        return instance;
    }

    /**
     * 线程安全，但是性能堪忧
     * @return
     */
    public static synchronized SingletonExa getInstance2() {
        if(instance == null) {
            instance = new SingletonExa();
        }
        return instance;
    }

    //单例对象
    private static volatile SingletonExa instance3 = null;
    /**
     * 线程安全，性能也好
     * @return
     */
    public static  SingletonExa getInstance3() {
        if(instance3 == null) {
            synchronized (SingletonExa.class){
                if(instance3==null)
                     instance3 = new SingletonExa();
            }
        }
        return instance3;
    }

}
